package com.coder.algorithm.offer_2;

import java.util.Arrays;

/**
 * 股票的最大利润
 *
 * @author yuhushuan
 * @date 2020/7/4 00:07
 */
public class _63_1_MaximalProfit {

    private static int maxProfit(int[] numbers) {
        if (numbers == null || numbers.length < 2) {
            return 0;
        }

        int minPrice = numbers[0];
        int max = 0;
        for (int i = 1; i < numbers.length; ++i) {
            if (numbers[i] < minPrice) {
                minPrice = numbers[i];
            }
            int currentDiff = numbers[i] - minPrice;
            if (currentDiff > max) {
                max = currentDiff;
            }
        }
        return max;
    }

    public static void main(String[] args) {
        // 功能测试
        // 无序
        print(new int[]{9, 11, 8, 5, 7, 12, 16, 14});
        print(new int[]{5, 7, 12, 16, 9, 11, 8, 14});

        print(new int[]{7,1,5,3,6,4});
        // 递增
        print(new int[]{1, 2, 3, 4, 5, 6, 8});
        // 递减
        print(new int[]{8, 6, 5, 4, 3, 2, 1});
        print(new int[]{7,6,4,3,1});

        // 边界值测试
        print(new int[]{8, 12});

        print(null);
    }

    private static void print(int[] number) {
        System.out.println("股票价格：" + Arrays.toString(number));
        System.out.println("最大利润：" + maxProfit(number));
        System.out.println();
    }
}
